import React, {useState, useEffect} from 'react'
import {Input, Button, List} from 'antd'
import { connect } from 'react-redux'
import Axios from 'axios'

const App = ({data, handelAdd, handelInitTodo, handelDel}) => {

  const [inputVal, setInputval] = useState('')
  // 由于页面刷新，数据不能永远保存，解决办法->页面初始化进行数据获取
  useEffect(() => {// 构造函数，生命钩子函数应用
    handelInitTodo()
  }, [handelInitTodo])

  return (
    <div style={{width:'50%',margin:'30px auto'}}>
      <div style={{display: 'flex'}}>
        <Input placeholder="Basic usage" value={inputVal} onChange={(e) => {
          setInputval(e.target.value)
        }}/>
        <Button type="primary" onClick={() => {
          handelAdd(inputVal)
        }}>ADD</Button>
        </div>
        <div>
            <List
              bordered
              dataSource={data}
              renderItem={(item, index) => (
                <List.Item onClick={() => {
                  handelDel(item.id, index)
                }}> {item.name}</List.Item>
              )}
            />
        </div>
    </div>
  )
}

export default connect(
  (state) => {
    return {
      data: state.todos
    }
  },
  (dispatch) => {
    return{
      handelAdd(value) {
        Axios.post('http://localhost:9090/todos', {
          name: value
        }).then(res => {
          const {data} = res
          //dispatch放在axios发送完后执行写入仓库动作
          dispatch({
            type: 'ADD_TODO',
            data
          })
        })
        
      },
      handelInitTodo () {// 初始化todo数据
        Axios.get('http://localhost:9090/todos').then(res => {
          const {data} = res
          dispatch({
            type: 'INIT_TODO',
            data
          })
        })
      },
      handelDel(id, index) {
        Axios.delete(`http://localhost:9090/todos/${id}`).then(res => {
          const {data} = res
          console.log(data)
          dispatch({
            type: 'DEL_TODO',
            index: index
          })
        })
        
      }
    }
  }
)(App)